package com.wink.admin.interceptor;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.SystemClock;
import com.wink.admin.utils.IpUtils;
import com.wink.admin.utils.JsonUtil;
import com.wink.admin.utils.RequestUtils;
import com.wink.admin.utils.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 日志拦截器
 *
 * @author donaldhan
 */
public class LogInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

    private long start;
    private long timing;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) {
        MDC.put("requestId", IdUtil.fastSimpleUUID());
        // 计算执行耗时
        start = SystemClock.now();
        Map<String, Object> requestMapData = new HashMap<>(7);
        requestMapData.put("requestURI", request.getScheme() + "://" + request.getServerName() + request.getRequestURI());
        requestMapData.put("requestMethod", request.getMethod());
        requestMapData.put("requestContentType", request.getContentType());
        requestMapData.put("requestIp", IpUtils.getIpAddress(request));
        requestMapData.put("requestHeader", RequestUtils.getHeaders(request));
        requestMapData.put("requestCharacterEncoding", request.getCharacterEncoding());
        requestMapData.put("requestData", RequestUtils.getRequestParameter(request));
        logger.info(JsonUtil.toStr(requestMapData));
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        timing = SystemClock.now() - start;
        logger.info("Time:{}ms,results:{}", timing, JsonUtil.toStr(ResponseUtils.getResult()));
        timing = 0;
    }

}
